package com.example.index.ui

import android.util.Log
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView
import com.example.index.extension.dp

class DailyTaskLayoutManager : RecyclerView.LayoutManager() {


    var overlayCountMax = 2

    var scaleStep: Float = 0.03f

    var init = false

    fun setMaxOverlayCount(maxCount: Int) {
        overlayCountMax = maxCount
        requestLayout()
    }

    override fun onAdapterChanged(oldAdapter: RecyclerView.Adapter<*>?, newAdapter: RecyclerView.Adapter<*>?) {
        super.onAdapterChanged(oldAdapter, newAdapter)
        init = false
    }

    val TAG = "DailyTaskLayoutManager"
    override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State?) {
        super.onLayoutChildren(recycler, state)

        detachAndScrapAttachedViews(recycler)

        if (itemCount <= 0) return


        var pos = if (itemCount < overlayCountMax) {
            itemCount - 1
        } else overlayCountMax - 1


        while (pos >= 0) {

            val child = recycler.getViewForPosition(pos)

            addView(child)
            measureChildWithMargins(child, 0, 0)


            child.pivotX = child.measuredWidth / 2f
            child.pivotY = child.measuredHeight / 2f

            val xScale = if (child.scaleX == 1f) 1f + 2 * scaleStep * pos else 1f
            val yScale = if (child.scaleY == 1f) 1f - scaleStep * pos else 1f


            val lp = child.layoutParams as RecyclerView.LayoutParams


            val w: Int = if (lp.width <= 0) (child.measuredWidth * xScale).toInt() else lp.width
            val h = if (lp.width <= 0) (child.measuredHeight * yScale).toInt() else lp.height


            Log.i(TAG, "onLayoutChildren: $pos $xScale  $yScale $w $h ")

            //根据最后的拉伸量来放置到中心位置

            layoutDecoratedWithMargins(
                child,
                (width - w) / 2,
                (height - h) / 2,
                (width + w) / 2,
                (height + h) / 2
            )

            if (lp.width <= 0) {
                lp.width = w
                lp.height = h
                child.layoutParams = lp
            }

            //elevation 和 z 都用一样的值
            val ez = 15.dp - pos.dp
            ViewCompat.setElevation(child, ez)
            ViewCompat.setTranslationZ(child, ez)

            child.translationY = child.measuredHeight * (pos * scaleStep) / 2f

            pos--
        }


    }

    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {

        return RecyclerView.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
    }


}